#!/bin/bash
set -e

while getopts  ":w:c:p:g:f:" opts
do
	case  $opts  in
	w)
		window=$OPTARG
		;;
	g)
        ref_genome=$OPTARG
        ;;
	p)
        out_prefix=$OPTARG
        ;;
	f)
        filt=true
		f_arg=$OPTARG
        ;;
	\?)
		echo `basename $0` "[-p out_prefix] <sample.bam> <ref.bam>"
		exit 1
		;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then
	echo `basename $0` '[-p out_prefix] <sample.bam> <ref.bam>'
	exit 1
fi


#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
#-----------------------------------------------


if [ -z "$window" ]; then
	window=200000
fi

samtools view -F4 $1 |awk '{print $3"\t"$4}' > $out_prefix.cnvseq_x.txt
samtools view -F4 $2 |awk '{print $3"\t"$4}' > $out_prefix.cnvseq_y.txt

cnv-seq.pl --test $out_prefix.cnvseq_x.txt \
--ref $out_prefix.cnvseq_y.txt \
--genome human

mv $out_prefix.cnvseq_x.txt-vs-$out_prefix.cnvseq_y.txt.*.cnv $out_prefix.cnv_cnvseq.txt
mv $out_prefix.cnvseq_x.txt-vs-$out_prefix.cnvseq_y.txt.*.count $out_prefix.count_cnvseq.txt

Rscript ${tools_path}/script/cnv_cnvseq.r --args \
$out_prefix.cnv_cnvseq.txt \
$sample_name

rename 1 $out_prefix 1.cnv.cnvseq.pdf # if same name, mv will wrong and exit

bak.sh $out_prefix.cnv.cnvseq.pdf